﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GMLogging;
using ThouShaltNotBrick.Models;
using System.IO;
using System.Xml.Linq;

namespace ThouShaltNotBrick.DataAccess
{
    public static class LevelXmlWriter
    {
        #region Methods
        public static void Write(string pLevelFilePath, LevelData pLevelData)
        {
            FileStream stream = null;
            try
            {
                stream = new FileStream(pLevelFilePath, FileMode.Create, FileAccess.Write);
                XDocument levelDataXDocument = CreateXDocument(pLevelData);
                levelDataXDocument.Save(stream);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                throw;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }

        private static XDocument CreateXDocument(LevelData pLevelData)
        {
            XDocument levelXDocument = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"));

            XElement levelXElement = new XElement(
                LevelXmlConstants.TAG_LEVEL,
                new XAttribute(LevelXmlConstants.TAG_LEVEL_ATTRIBUTE_NAME, pLevelData.Name));

            XElement bricksXElement = new XElement(LevelXmlConstants.TAG_BRICKS);
            List<BrickData> brickList = pLevelData.GetBricks();
            foreach (BrickData brick in brickList)
            {
                XElement brickXElement = new XElement(
                    LevelXmlConstants.TAG_BRICK,
                    new XAttribute(LevelXmlConstants.TAG_BRICK_ATTRIBUTE_TYPE, brick.TypeName),
                    new XAttribute(LevelXmlConstants.TAG_BRICK_ATTRIBUTE_ROW, brick.Row),
                    new XAttribute(LevelXmlConstants.TAG_BRICK_ATTRIBUTE_COLUMN, brick.Column),
                    new XAttribute(LevelXmlConstants.TAG_BRICK_ATTRIBUTE_INITIAL_STATE, brick.InitialBrickStateIndex));
                bricksXElement.Add(brickXElement);
            }

            levelXElement.Add(bricksXElement);

            levelXDocument.Add(levelXElement);

            return levelXDocument;
        }
        #endregion
    }
}